package client;

import common.RPCRequest;
import common.RPCResponse;
import register.ServiceRegister;
import register.ZkServiceRegister;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SimpleClient implements RPCClient{
    private String ip;
    private Integer port;
    private ServiceRegister serviceRegister;
    public SimpleClient(){
        this.serviceRegister = new ZkServiceRegister();
    }
    public RPCResponse sendRequest(RPCRequest request){
        InetSocketAddress address = serviceRegister.serviceDiscovery(request.getInterfaceName());
        this.ip = address.getHostName();
        this.port = address.getPort();
        try {
            Socket socket = new Socket(ip, port);
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            outputStream.writeObject(request);
            outputStream.flush();
            RPCResponse response = (RPCResponse) inputStream.readObject();
            return response;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}
